package com.bite.Demo;

import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

public class Demo02_DriverManage {
    public static void main(String[] args) throws SQLException {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            //1.加载数据库驱动,数据库驱动是由数据库厂商提供的，这样MySQL提供的jar包就和Java建立连接
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.创建数据库连接(/左边是数据库主机的地址和端口号，右边是要访问的数据库名)
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/school_cafeteria?" +
                            "characterEncoding=utf8",
                    "root","mazixuan");

            //3.创建statement对象
            statement = connection.createStatement();
            //4.定义sql语句
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入你要查询的姓名");
            String inputName = scanner.nextLine();
            String sql = "select student_id,student_name,gender,college,major,class,telephone from student where student_name = '"+inputName+"'";
            //5.执行sql语句
            resultSet = statement.executeQuery(sql);
            //6.遍历结果集
            while(resultSet.next()){
                long student_id = resultSet.getLong(1);
                String student_name = resultSet.getString(2);
                String gender = resultSet.getString(3);
                String college = resultSet.getString(4);
                String major = resultSet.getString(5);
                String class_name = resultSet.getString(6);
                String telephone = resultSet.getString(7);
                //7.输出结果
                System.out.println(MessageFormat.format("学生id={0} 学生姓名={1} " +
                        "性别={2} 学院={3} 主修专业={4}" +
                        " 班级名={5} 电话号码={6}",
                        student_id,student_name,gender,college,major,class_name,telephone));
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
}
